package com.test.mooan.labama.activity_fragment_boom.login_boom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.test.mooan.labama.R;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.ln_boom.LnMainActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.CountryInfo_boom;
import com.test.mooan.labama.bean_boom.process_boom.ProcessInfo_boom;
import com.test.mooan.labama.dialog_boom.CustomerServiceDialog_boom;
import com.test.mooan.labama.utils_boom.Stringutil_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpManager_boom;
import com.test.mooan.labama.view_boom.widget_boom.BoomEditText;

public class MobileVerificationActivity extends BaseActivity_boom {

    private BoomEditText mobileEt;
    private TextView mobileBtn;
    private TextView typeTitleTv;

    private View telegramView,smsView,telegramBotView;
    private ImageView telegramIv,smsIv,telegramBotIv;
    private TextView telegramTv,smsTv, telegramBotTv;
    private ImageView telegramCheckIv, smsCheckIv,telegramBotCheckIv;

    private TextView codeTitleTv;
    private View codeInputView;

    private BoomEditText codeEt;
    private TextView getCodeBtn;

    private final String Type_SMS = "SMS";
    private final String Type_Telegram = "TELEGRAM";
    private final String Type_TelegramBot = "TGBOT";

    private String selectedType = Type_Telegram;

    private String confirmMobile;
    private String confirmType;

    private boolean btnIsEdit = true;

    private boolean toHomeFlag = false;

    private final View.OnClickListener getCodeClick = v -> {

        btnIsEdit = true;
        mobileEt.setEnabled(false);
        mobileBtn.setBackgroundResource(R.drawable.ic_bg_btn_border);
        mobileBtn.setText(getString(R.string.edit));
        mobileEt.clearFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) imm.hideSoftInputFromWindow(mobileEt.getWindowToken(), 0);
        mobileEt.setFocusableInTouchMode(false);


        String mobile = mobileEt.gtTextString();

        if (TextUtils.isEmpty(mobile)){
            showToast_boom(getString(R.string.enter_phonenum_tip));
            return;
        }

        UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_GET_CODE_CLICK");

        HttpManager_boom.getInstance().getOtpCode(mobile,selectedType);

    };

    private boolean phoneNumberHintFlag = true;

    private final ActivityResultLauncher<IntentSenderRequest> phoneNumberHintLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                try {

                    String mobile = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.getData());

                    if (TextUtils.isEmpty(mobile)) return;

                    String areaCodeText = CountryInfo_boom.gInstance().gAreaCode();

                    if (mobile.startsWith(areaCodeText)) mobileEt.setText(mobile.replace(areaCodeText,""));
                    else mobileEt.setText(mobile);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_verification);

        toHomeFlag = getIntent().getBooleanExtra("toHomeFlag",false);

        findViewById(R.id.amv_customer_service).setOnClickListener(v -> {
            UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_CUSTOMER_SERVICE_CLICK");
            new CustomerServiceDialog_boom(this).show();
        });

        TextView areaCodeTv = findViewById(R.id.amv_area_code);
        areaCodeTv.setText(CountryInfo_boom.gInstance().gAreaCode());

        mobileEt = findViewById(R.id.amv_mobile);
        mobileBtn = findViewById(R.id.amv_mobile_btn);
        typeTitleTv = findViewById(R.id.amv_type_title);
        telegramView = findViewById(R.id.amv_view_telegram);
        smsView = findViewById(R.id.amv_view_sms);
        telegramBotView = findViewById(R.id.amv_view_telegram_bot);
        telegramIv = findViewById(R.id.amv_icon_telegram);
        smsIv = findViewById(R.id.amv_icon_sms);
        telegramBotIv = findViewById(R.id.amv_icon_telegram_bot);
        telegramTv = findViewById(R.id.amv_tv_telegram);
        smsTv = findViewById(R.id.amv_tv_sms);
        telegramBotTv = findViewById(R.id.amv_tv_telegram_bot);
        telegramCheckIv = findViewById(R.id.amv_icon_telegram_check);
        smsCheckIv = findViewById(R.id.amv_icon_sms_check);
        telegramBotCheckIv = findViewById(R.id.amv_icon_telegram_bot_check);
        codeEt = findViewById(R.id.amv_et_code);
        getCodeBtn = findViewById(R.id.amv_get_code_btn);

        codeTitleTv = findViewById(R.id.amv_tv_code_title);
        codeInputView = findViewById(R.id.amv_view_code_input);

        mobileEt.stEventWord("VERIFICATION_MOBILE_INPUT");
        codeEt.stEventWord("VERIFICATION_CODE_INPUT");

        if (ProcessInfo_boom.getInstance().gTelegramFlag()){

            telegramView.setOnClickListener(v -> {
                if (Type_Telegram.equalsIgnoreCase(selectedType)) return;
                UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_TELEGRAM_CLICK");
                selectTelegram();
            });

            selectTelegram();

        }else telegramView.setVisibility(View.GONE);

        if (ProcessInfo_boom.getInstance().gSmsFlag()){

            smsView.setOnClickListener(v -> {
                if (Type_SMS.equalsIgnoreCase(selectedType)) return;
                UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_SMS_CLICK");
                selectSms();
            });

            if (!ProcessInfo_boom.getInstance().gTelegramFlag()) selectSms();

        }else smsView.setVisibility(View.GONE);

        if (ProcessInfo_boom.getInstance().gTelegramBotFlag()){

            telegramBotView.setOnClickListener(v -> {
//                if (Type_TelegramBot.equalsIgnoreCase(selectedType)) return;
                UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_TELEGRAM_BOT_CLICK");
                selectTelegramBot();
            });

            if (!ProcessInfo_boom.getInstance().gSmsFlag() && !ProcessInfo_boom.getInstance().gTelegramFlag()){

                selectedType = Type_TelegramBot;
                confirmType = Type_TelegramBot;
                typeTitleTv.setText(getString(R.string.mobile_verification_type_title,getString(R.string.telegram_bot)));

                telegramView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
                telegramIv.setImageResource(R.drawable.icon_telegram_gray);
                telegramTv.setTextColor(Color.parseColor("#FF8E9096"));
                telegramCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

                smsView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
                smsIv.setImageResource(R.drawable.icon_sms_gray);
                smsTv.setTextColor(Color.parseColor("#FF8E9096"));
                smsCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

                telegramBotView.setBackgroundResource(R.drawable.bg_otp_type_selected);
                telegramBotIv.setImageResource(R.drawable.icon_robot_white);
                telegramBotTv.setTextColor(Color.WHITE);
                telegramBotCheckIv.setImageResource(R.drawable.icon_otp_type_check_true);

                codeTitleTv.setVisibility(View.GONE);
                codeInputView.setVisibility(View.GONE);

            }

        }else telegramBotView.setVisibility(View.GONE);

        confirmType = selectedType;

        confirmMobile = UserInfoHelper_boom.gInstance().gMobile();
        mobileEt.setText(confirmMobile);

        mobileEt.addOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus && phoneNumberHintFlag){

                phoneNumberHintFlag = false;

                GetPhoneNumberHintIntentRequest request = GetPhoneNumberHintIntentRequest.builder().build();

                Identity.getSignInClient(this).getPhoneNumberHintIntent(request)
                        .addOnSuccessListener(result -> {
                            try {
                                phoneNumberHintLauncher.launch(new IntentSenderRequest.Builder(result.getIntentSender()).build());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        })
                        .addOnFailureListener(e -> Log.e("=Login", "Phone number hint failed"));

            }

        });

        if (ProcessInfo_boom.getInstance().gMobileEditFlag()){
            mobileBtn.setVisibility(View.VISIBLE);
            mobileBtn.setOnClickListener(v -> {

                if (btnIsEdit){

                    btnIsEdit = false;

                    mobileEt.setEnabled(true);
                    UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_EDIT_MOBILE_CLICK");
                    mobileBtn.setBackgroundResource(R.drawable.ic_bg_btn_2);
                    mobileBtn.setText(getString(R.string.confirm));

                    mobileEt.setFocusableInTouchMode(true);
                    mobileEt.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) imm.showSoftInput(mobileEt, InputMethodManager.SHOW_IMPLICIT);
                    mobileEt.setSelection(mobileEt.gtTextString().length());

                }else {

                    btnIsEdit = true;

                    mobileEt.setEnabled(false);
                    UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_CONFIRM_MOBILE_CLICK");
                    mobileBtn.setBackgroundResource(R.drawable.ic_bg_btn_border);
                    mobileBtn.setText(getString(R.string.edit));

                    mobileEt.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) imm.hideSoftInputFromWindow(mobileEt.getWindowToken(), 0);
                    mobileEt.setFocusableInTouchMode(false);

                }

            });
        }else mobileBtn.setVisibility(View.GONE);

        codeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                String mobile = mobileEt.gtTextString();
                String code = codeEt.gtTextString();
                if (TextUtils.isEmpty(mobile)) return;
                if (TextUtils.isEmpty(code) || s.length()<4) return;
                UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_OTP_DONE");
                HttpManager_boom.getInstance().checkMobile(confirmMobile,confirmType,code);
            }
        });

        getCodeBtn.setOnClickListener(getCodeClick);

        //Next
        findViewById(R.id.amv_next).setOnClickListener(v -> {

            String mobile = mobileEt.gtTextString();
            String code = codeEt.gtTextString();

            if (TextUtils.isEmpty(mobile)){
                showToast_boom(getString(R.string.enter_phonenum_tip));
                return;
            }

            if (TextUtils.isEmpty(code) && (!Type_TelegramBot.equalsIgnoreCase(selectedType))){
                showToast_boom(getString(R.string.enter_vercode_tip));
                return;
            }

            UserInfoHelper_boom.gInstance().addEventPoint("VERIFICATION_NEXT_CLICK");
            HttpManager_boom.getInstance().saveUserPointForBatch();
            HttpManager_boom.getInstance().checkMobile(confirmMobile,confirmType,code);

        });

    }

    private void selectTelegram(){

        selectedType = Type_Telegram;
        typeTitleTv.setText(getString(R.string.mobile_verification_type_title,getString(R.string.telegram)));

        telegramView.setBackgroundResource(R.drawable.bg_otp_type_selected);
        telegramIv.setImageResource(R.drawable.icon_telegram_white);
        telegramTv.setTextColor(Color.WHITE);
        telegramCheckIv.setImageResource(R.drawable.icon_otp_type_check_true);

        smsView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
        smsIv.setImageResource(R.drawable.icon_sms_gray);
        smsTv.setTextColor(Color.parseColor("#FF8E9096"));
        smsCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

        telegramBotView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
        telegramBotIv.setImageResource(R.drawable.icon_robot_gray);
        telegramBotTv.setTextColor(Color.parseColor("#FF8E9096"));
        telegramBotCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

        codeTitleTv.setVisibility(View.VISIBLE);
        codeInputView.setVisibility(View.VISIBLE);

    }

    private void selectSms(){

        selectedType = Type_SMS;
        typeTitleTv.setText(getString(R.string.mobile_verification_type_title,getString(R.string.sms)));

        telegramView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
        telegramIv.setImageResource(R.drawable.icon_telegram_gray);
        telegramTv.setTextColor(Color.parseColor("#FF8E9096"));
        telegramCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

        smsView.setBackgroundResource(R.drawable.bg_otp_type_selected);
        smsIv.setImageResource(R.drawable.icon_sms_white);
        smsTv.setTextColor(Color.WHITE);
        smsCheckIv.setImageResource(R.drawable.icon_otp_type_check_true);

        telegramBotView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
        telegramBotIv.setImageResource(R.drawable.icon_robot_gray);
        telegramBotTv.setTextColor(Color.parseColor("#FF8E9096"));
        telegramBotCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

        codeTitleTv.setVisibility(View.VISIBLE);
        codeInputView.setVisibility(View.VISIBLE);
    }

    private void selectTelegramBot(){

        selectedType = Type_TelegramBot;
        confirmType = Type_TelegramBot;
        typeTitleTv.setText(getString(R.string.mobile_verification_type_title,getString(R.string.telegram_bot)));

        telegramView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
        telegramIv.setImageResource(R.drawable.icon_telegram_gray);
        telegramTv.setTextColor(Color.parseColor("#FF8E9096"));
        telegramCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

        smsView.setBackgroundResource(R.drawable.bg_otp_type_unselected);
        smsIv.setImageResource(R.drawable.icon_sms_gray);
        smsTv.setTextColor(Color.parseColor("#FF8E9096"));
        smsCheckIv.setImageResource(R.drawable.icon_otp_type_check_false);

        telegramBotView.setBackgroundResource(R.drawable.bg_otp_type_selected);
        telegramBotIv.setImageResource(R.drawable.icon_robot_white);
        telegramBotTv.setTextColor(Color.WHITE);
        telegramBotCheckIv.setImageResource(R.drawable.icon_otp_type_check_true);

        codeTitleTv.setVisibility(View.GONE);
        codeInputView.setVisibility(View.GONE);

        HttpManager_boom.getInstance().getTgBotUrl(mobileEt.gtTextString());

    }

    @SuppressLint("SetTextI18n")
    public void onGetCodeSuccessful(){

        confirmMobile = Stringutil_boom.getSafeString(mobileEt.gtTextString());
        confirmType = selectedType;

        getCodeBtn.setBackgroundResource(R.drawable.ic_round_corner_gray_llll_6dp);
        getCodeBtn.setTextColor(Color.parseColor("#FFD6D9E5"));
        getCodeBtn.setOnClickListener(null);

        new Thread(() -> {
            int count = 60;
            while (count-->0){
                final int fc = count;
                if (!isClose()){
                    runOnUiThread(() -> getCodeBtn.setText(fc+" s"));
                }
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (!isClose()){
                runOnUiThread(() -> {
                    getCodeBtn.setTextColor(getColor(R.color.blue_boom));
                    getCodeBtn.setText(getString(R.string.get_code));
                    getCodeBtn.setBackgroundResource(R.drawable.ic_bg_btn_border);
                    getCodeBtn.setOnClickListener(getCodeClick);
                });
            }

        }).start();

    }

    public void onCheckSuccessful(){
        UserInfoHelper_boom.gInstance().sMobile(confirmMobile);
        HttpManager_boom.getInstance().requestUserProcess();
    }

    public void onCheckFail(){

        if (Type_TelegramBot.equalsIgnoreCase(selectedType)){
            HttpManager_boom.getInstance().getTgBotUrl(mobileEt.gtTextString());
        }

    }

    public void onTgBotUrlResponse(String url){
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(Stringutil_boom.getSafeString(url));
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    @Override
    public void onUserProcessResponse() {
        if (!ProcessInfo_boom.getInstance().isNeedVerification()){
            if (toHomeFlag) startActivity(new Intent(this,LnMainActivity_boom.class));
            finish();
        }else {
            showToast_boom(getString(R.string.tips_ver_failed));
        }
    }

    @Override
    public void onBackPressed() {}

    @Override
    protected void onStop() {
        super.onStop();
        if (mobileEt!=null) mobileEt.clearFocus();
        if (codeEt!=null) codeEt.clearFocus();
    }
}